import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
//引入element-ui
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import "./assets/style/base.css";
import "./assets/style/reset.css";
//引入iconfont
import "./assets/iconfont/iconfont.css";
//引入侧边栏插件subMenu
import subMenu from "qf-sub-menu";

//导入进度条插件nprogress
import NProgress from "nprogress";
import "nprogress/nprogress.css";
//引入eventBus
import bus from "./untils/bus"
Vue.prototype.$bus = bus;

//引入权限菜单的鉴权方法
import {permission} from "./untils/recursionRoutes"
Vue.prototype.$has = permission;

Vue.config.productionTip = false;
//全局使用element-ui
Vue.use(ElementUI);
//全局使用侧边栏插件subMenu
Vue.use(subMenu);

//自定义指令 判断用户的按钮权限
Vue.directive("has",{
  bind(el,binding,VNode){
    // console.log(el);
    // console.log(binding);
    let buttons = localStorage.getItem("bms-permission-button")
buttons = JSON.parse(buttons)
    if(!permission(buttons,binding.value)){//得到所有没有权限的按钮
      // console.log(el);
      //先储存el.className
      let className = el.className
      el.className = className +" "+"is-disabled"
      el.disabled = true
    }
  }
}) 

//路由守卫(路由前置钩子)
router.beforeEach((to, from, next) => {
  NProgress.start(); //进度条出现
  // console.log(to);
  // console.log(from);
  // next()
  // 用户登录之后,localstorage中由token,由此判断用户是否登录
  let token = localStorage.getItem("bms-token");
  if (token) {
    if (store.state.menuList.length == 0) {
      // 判断vuex(store)中是否有用户合法的动态路由
      //如果没有就调用store的actions中的FETCH_MENULIST
      store.dispatch("FETCH_MENULIST").then(() => {
        next({ path: to.path }); //留心:next里面要传参数即要进入的页面信息,因为next执行后,当前的to路由将会废弃,path传入to的path,虽然跳转的还是相同路由,这样还可以确保addRoutes已经生效
      });
    } else {
      next(); //如果有就放行
    }
  } else {
    //如果是登录,注册页面,也放行
    if (to.path === "/login") {
      next();
    } else {
      //访问的不是登录页,就跳转到登录页
      next({ path: "/login" });
    }
  }
});

//路由后置钩子处理面包屑
router.afterEach((to, from) => {
  // console.log(to);
  let crumblist = to.matched.slice(1);
  // console.log(crumblist);
  store.commit("SET_CRUMBS", crumblist);
  NProgress.done(); //进度条消失
});

import "./untils/recursionRoutes";
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");
